package o2o.web.actions.company;


import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.DateUtils;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import o2o.cache.company.SysCityCompanyMemory;
import o2o.cache.company.SysCityCompanyUserRelationMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.config.memcached.MemcacheUtil;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.company.SYS_COMPANY_USER_TYPE;
import o2o.dao.PO.company.SysCityCompanyInfo;
import o2o.dao.PO.company.SysCityCompanyUser;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.company.SysCityCompanyUserVO;
import o2o.system.data.SYS_SETTINGS;
import o2o.web.actions.user.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @User: @Created by yangtk
 * @Date: @Date 2019/7/16 9:55
 * @Classname: SysCityCompanyUserController
 * @To 代理添加员工信息
 */
@Controller
public class SysCityCompanyUserController {

    // 添加一个员工
    @RequestMapping(value = "/company/user/add", method = RequestMethod.POST)
    @ResponseBody
    public String createCompanyUser(String token, Long companyId
            , String username, String signature, String telPhone, String phone2, String sex, String address, String name
            , String province, String city, String county, Integer companyUserType) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        SysCityCompanyInfo companyInfo = null;

        if (companyId == null || companyId < 1) {
            //
            companyInfo = SysCityCompanyMan.getByCompanyUsername(user.getUsername());
            companyId = companyInfo == null ? null : companyInfo.getId();
        } else {
            companyInfo = SysCityCompanyMemory.getInstance().getById(companyId);
        }
        int userType = UserType.COMPANY;
        if (SysCityCompanyMan.isSuperAdminCompany(companyInfo.getId())) {
            userType = UserType.SUPER_COMPANY;
        }
        if (companyInfo == null) {
            return AjaxResult.errorResult("未获取到公司信息");
        }

        UserInfo userInfo = User.getUserInfoByUsername(username);
        if (null == userInfo) { //系统中无该用户
            //新建管理员
            UserInfo u = new UserInfo(userType, username, name, signature, telPhone, phone2, sex,
                    province, city, county, address, user.getUsername());
            String phone = username;
            if (User.isPhoneLogin()) {
                username = User.getUniqueUserName(username);
            }
            u.setUsername(username); // 用户标识
            u.setPhone(phone);
            try {
                String psw = "123456";
                if (null != SYS_SETTINGS.SHOP_DEFAULT_PSW && 0 == 1 - SYS_SETTINGS.SHOP_DEFAULT_PSW) {
                    psw = phone.substring(5, 11);
                }
                ResultInfo resultInfo = User.addUser(u, psw);
                if (resultInfo == null || !resultInfo.isSuccess()) {
                    return AjaxResult.errorResult(resultInfo.getError());
                }
            } catch (Exception e) {
                return AjaxResult.errorResult("新增失败，请稍后再试");
            }
        } else {
            if (userInfo.getUserType() == UserType.USER) {
                username = userInfo.getUsername();
                // 修改用户类型为公司用户
                StringBuilder sb = new StringBuilder();
                sb.append("update ").append(PojoTables.UserInfo).append(" set usertype=").append(userType).append(" where delFlag = 0 and  username='").append(username).append("'");
                try {
                    UserDaoSql.getInstance().executeBySql(sb.toString());
                } catch (SQLException e) {
                    e.printStackTrace();
                    return AjaxResult.errorResult("新增失败，请稍后再试.");
                }
                //修改缓存
                UserInfoMemory.getInstance().modifyUserType(username, userType);
                try {
                    JMSNotify notifyII = JMSNotify.getInstance().setType(JMSTypeContent.USER_TYPE_MODIFY).setStr01(username).setInt01(userType);//o2o.business.jms  MQDataBusiness
                    JmsSender.setTopicSender(notifyII);
                } catch (Exception e) {
                }
            } else {
                return AjaxResult.errorResult("当前用户已存在");
            }
        }
        if (companyUserType != null && companyUserType == 3) {
            companyUserType = SYS_COMPANY_USER_TYPE.MANAGER;
        } else {
            companyUserType = SYS_COMPANY_USER_TYPE.STAFF;
        }
        long time = DateUtils.getCurrTime();
        // 添加公司的与员工的关联关系
        SysCityCompanyUser companyUser = new SysCityCompanyUser();
        companyUser.setUsername(username).setType(companyUserType).setCompanyId(companyInfo.getId()).setCreateUser(user.getUsername()).setCreateTime(time)
                .setDelFlag(0);
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.SYS_CITY_COMPANY_USER, companyUser);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("添加公司员工失败,请稍后重试");
        }

        // 公司员工缓存
        SysCityCompanyUserRelationMemory.getInstance().add(time);
        // 数据通讯
        JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SYS_CITY_COMPANY_USER_ADD).setLong01(time);
        JmsSender.setTopicSender(notify);
        return AjaxResult.successResult();
    }

    @RequestMapping(value = "/company/user/del", method = RequestMethod.POST)
    @ResponseBody
    public String createCompanyUser(String token, String username) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (StringUtils.isEmpty(username)) {
            return AjaxResult.errorResult("员工账号不能为空");
        }
        Long companyId = SysCityCompanyUserRelationMemory.getInstance().getCompanyIdByUsername(username);
        if (companyId == null) {
            return AjaxResult.errorResult("未获取到公司id信息");
        }
        // 删除公司与用户的关联关系
        StringBuilder delRelationSql = new StringBuilder();
        delRelationSql.append("update ").append(PojoTables.SYS_CITY_COMPANY_USER).append(" set delFlag = 1 ,updateUser ='")
                .append(user.getUsername()).append("'").append(" where delFlag = 0 and username='").append(username).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(delRelationSql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除失败,请稍后重试");
        }
        // cache
        SysCityCompanyUserRelationMemory.getInstance().del(username);
        // 数据通讯
        JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SYS_CITY_COMPANY_USER_DELETE).setStr01(username);
        JmsSender.setTopicSender(notify);

        UserInfo info = UserInfoMemory.getInstance().getUserInfo(username);
        if (info != null && (info.getUserType() == UserType.COMPANY || info.getUserType() == UserType.SUPER_COMPANY)) {
            // 降级到user
            StringBuilder updateUserSql = new StringBuilder();
            updateUserSql.append("update ").append(PojoTables.UserInfo)
                    .append(" set updateUser ='").append(user.getUsername()).append("'")
                    .append(", userType =").append(UserType.USER).append(" where username ='").append(username)
                    .append("' and delFlag = 0");
            try {
                UserDaoSql.getInstance().executeBySql(updateUserSql.toString());
                UserInfoMemory.getInstance().modifyUserInfo(username);
                try {
                    JMSNotify notify2 = JMSNotify.getInstance().setType(JMSTypeContent.USER_INFO_MODIFY).setStr01(username);
                    JmsSender.setTopicSender(notify2);
                } catch (Exception e) {
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 将用户token剔除
        MemcacheUtil.removeByUsername(username); // 删除token

        return AjaxResult.successResult();
    }

    // 修改用户在公司的权限
    @RequestMapping(value = "/company/user/update", method = RequestMethod.POST)
    @ResponseBody
    public String modifyCompanyUser(String token, String username, Integer companyUserType) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (StringUtils.isEmpty(username)) {
            return AjaxResult.errorResult("用户账号不能为空");
        }
        SysCityCompanyInfo usernameCompany = SysCityCompanyMan.getByCompanyUsername(username);
        if (usernameCompany == null) {
            return AjaxResult.errorResult("未获取到公司");
        }
        SysCityCompanyUser companyUserByUsername = SysCityCompanyUserRelationMemory.getInstance().getSysCityCompanyUserByUsername(username);
        if (companyUserByUsername == null) {
            return AjaxResult.errorResult("未获取到公司关心信息");
        }
        if (companyUserType != null && companyUserType == SYS_COMPANY_USER_TYPE.MANAGER) {
            companyUserType = SYS_COMPANY_USER_TYPE.MANAGER;
        } else {
            companyUserType = SYS_COMPANY_USER_TYPE.STAFF;
        }
        if (companyUserType == companyUserByUsername.getType()) {
            return AjaxResult.successResult();
        }
        try {
            SysCityCompanyMan.updateSysCityCompanyUser(username, companyUserType, user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败,请稍后重试");
        }

        return AjaxResult.successResult();
    }


    // 获取公司的员工列表
    @RequestMapping(value = "/company/user/list", method = RequestMethod.POST)
    @ResponseBody
    public String listOfCompanyUserByCompanyId(String token, Long companyId, String username) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        SysCityCompanyInfo companyInfo = null;
        if (companyId == null || companyId < 1) {
            companyInfo = SysCityCompanyMan.getByCompanyUsername(user.getUsername());
            if (companyInfo == null) {
                return AjaxResult.errorResult("未获取到公司信息");
            }
            companyId = companyInfo.getId();
        }
        if (companyId == null) {
            return AjaxResult.errorResult("公司id不能为空");
        }
        List<SysCityCompanyUserVO> list = null;
        try {
            list = SysCityCompanyMan.listOfCompanyUserVOByCompanyId(companyId, username);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败,请稍后重试");
        }
        if (list != null && !list.isEmpty()) {
            return AjaxResult.successResult(list.size(), list);
        }
        return AjaxResult.successResult();
    }


}
